#include<iostream>
#include<memory>
#include<cassert>
#include<fstream>
#include<sys/types.h>
#include<sys/stat.h>
#include <fcntl.h>

#include"HttpServer.hpp"
#include"Usage.hpp"
#include"Util.hpp"

//定义根目录和默认首页
#define ROOT "./wwwroot"
#define HOMEPAGE  "index.html"

//目的:构建一个http相应
void HandlerHttpRequest(int sockfd)
{
    char buffer[1024];
    //从套接字中读取请求数据
    ssize_t s = recv(sockfd,buffer,sizeof(buffer)-1,0);
    if(s>0)
    {
        buffer[s]=0;
    }

    //将报文存储到vline中进行处理
    std::vector<std::string> vline;
    Util::cutString(buffer,"\n",&vline);//按行存储

    std::vector<std::string> vblock;
    Util::cutString(vline[0]," ",&vblock);//

    std::string file = vblock[1];
    std::string target = ROOT;

    //处理客户端发送的请求
    if(file =="/") file = "/index.html";
    target +=file;
    std::cout <<target<<std::endl;

    //读取客户端请求
    std::string content;
    std::ifstream in(target);
    if(in.is_open())
    {
        std::string line;
        while(std::getline(in,line))
        {
            content +=line;
        }
        in.close();
    }

    //回复报文(服务器返回给客户端的信息)
    std::string HttpResponse;
    //2.0版本（增加重定向功能）
    if(content.empty())
    {
        HttpResponse = "HTTP/1.1 301 Moved Permanently\r\n";
        //重定向到其他网页
        HttpResponse +="Location:https://youku.com/\r\n";
    }
    else
    {
        HttpResponse = "HTTP/1.1 200 OK\r\n";
        HttpResponse+=("Content-Type:text/html\r\n");
        HttpResponse+=("Conten-Length"+std::to_string(content.size())+"\r\n");
        HttpResponse+="Set-Cookie:cookie测试\r\n";
    }
    HttpResponse +="\r\n";
    HttpResponse +=content;

    //1.0 版本
    // if(content.empty()) HttpResponse = "HTTP/1.1 404 NotFound\r\n";
    // else HttpResponse ="HTTP/1.1 200 OK\r\n";
    // HttpResponse +="\r\n";
    // HttpResponse+=content;


    send(sockfd,HttpResponse.c_str(),HttpResponse.size(),0);
}

int main(int argc,char*argv[])
{
    if(argc!=2)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::unique_ptr<HttpServer> httpserver(new HttpServer(atoi(argv[1]),HandlerHttpRequest));
    httpserver->Start();
    return 0;
}